package com.gome.axwl.aoc.service.impl;

import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.common.util.DateUtil;
import com.gome.axwl.aoc.dao.IntegrationRuleDao;
import com.gome.axwl.aoc.entity.dto.IntegrationParamDto;
import com.gome.axwl.aoc.entity.dto.IntegrationRuleDto;
import com.gome.axwl.aoc.entity.dto.QueryResultAndModifyStatusDto;
import com.gome.axwl.aoc.entity.po.IntegrationRulePo;
import com.gome.axwl.aoc.service.IntegrationRuleService;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import com.gome.datasource.shard.annotation.ReadDatasource;
import com.gome.datasource.shard.annotation.WriteDatasource;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Description: 积分规则业务service实现类
 * @Auther: yinyuxin@gome.com.cn
 * @Date: 2018/4/25 13:59
 */
@Service("integrationRuleService")
public class IntegrationRuleServiceImpl  implements IntegrationRuleService {

    private final static Logger LOGGER=LoggerFactory.getLogger(IntegrationRuleServiceImpl.class);

    @Autowired
    private IntegrationRuleDao integrationRuleDao;


    @Override
    @ReadDatasource
    public ResultData<QueryResultAndModifyStatusDto<IntegrationRuleDto>> queryIntegrationRulesByType(String date, Byte ruleType) {
        if(null==date || "".equals(date)){
            date=DateUtil.date2String(new Date(),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        }
        QueryResultAndModifyStatusDto<IntegrationRuleDto> data=new QueryResultAndModifyStatusDto<>();
        IntegrationRulePo integrationRulePo=new IntegrationRulePo();
        integrationRulePo.setRuleDate(date);
        integrationRulePo.setRuleType(ruleType);

        List<IntegrationRulePo> integrationRulePoList;
        try {
           integrationRulePoList=integrationRuleDao.queryByList(integrationRulePo);
        } catch (Exception e) {
            LOGGER.error("查询积分规则信息失败，查询条件：{}，异常信息：{}", "date:"+date+";ruleType:"+ruleType, ExceptionUtils.getFullStackTrace(e));
            return new ResultData(ErrorCode.QUERY_FAILOR,ErrorCode.QUERY_FAILOR_MSG);
        }
        List<IntegrationRuleDto> integrationRuleDtos=BeanJsonUtil.listConvert(integrationRulePoList,IntegrationRuleDto.class);
        //判断当前数据是否支持修改（次月不允许修改）
        if (!CollectionUtils.isEmpty(integrationRuleDtos)){
            IntegrationRuleDto integrationRuleDto=integrationRuleDtos.get(0);
            data.setModify(this.checkModifyStatus(integrationRuleDto.getRuleDate()));
        }
        data.setData(integrationRuleDtos);
        return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @WriteDatasource
    public ResultData modifyIntegrationRules(IntegrationParamDto integrationParamDto) {
        //1：判断前端所传日期是否支持修改
        if (!this.checkModifyStatus(integrationParamDto.getDate())){
            return new ResultData(ErrorCode.UPDATE_FAILOR,"数据不支持修改");
        }
        //2: 批量删除已有的积分规则
        IntegrationRulePo integrationRuleParam=new IntegrationRulePo();
        integrationRuleParam.setRuleType(integrationParamDto.getType());
        integrationRuleParam.setRuleDate(integrationParamDto.getDate());
        integrationRuleDao.batchDeleteByTypeAndDate(integrationRuleParam);
        //3: 批量新增
        List<IntegrationRuleDto> integraRules = integrationParamDto.getIntegraRules();
        if (CollectionUtils.isEmpty(integraRules)){
            return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        }
        for (IntegrationRuleDto integrationRuleDto:integraRules){
            integrationRuleDto.setId(null);
            integrationRuleDto.setCreateDate(new Date());
            integrationRuleDto.setRuleDate(integrationParamDto.getDate());
            integrationRuleDto.setRuleType(integrationParamDto.getType());
            integrationRuleDto.setCreateUserCode(integrationParamDto.getModifyUserCode());
        }
        List<IntegrationRulePo> integrationRulePos=BeanJsonUtil.listConvert(integraRules,IntegrationRulePo.class);
        integrationRuleDao.batchInsert(integrationRulePos);
        return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @WriteDatasource
    public ResultData initIntegrationRules() {
        String nowDate=DateUtil.date2String(new Date(),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        IntegrationRulePo integrationRulePo=new IntegrationRulePo();
        integrationRulePo.setRuleDate(nowDate);
        //0：验证当前月是否已有数据
        List<IntegrationRulePo> integrationRulePosNow = integrationRuleDao.queryByList(integrationRulePo);
        if (integrationRulePosNow!=null&& integrationRulePosNow.size()>0){
            LOGGER.info("当月积分规则已有记录，跳过自动初始化");
            return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        }
        //1：获取上个月的整套积分规则信息
        String lastMonthDate=DateUtil.date2String(DateUtil.timeCalculation(new Date(),-1,1),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        integrationRulePo.setRuleDate(lastMonthDate);
        List<IntegrationRulePo> integrationRulePosLast = integrationRuleDao.queryByList(integrationRulePo);
        if (CollectionUtils.isEmpty(integrationRulePosLast)){
            throw new RuntimeException("获取上个月积分规则信息为null,请检查原因");
        }
        //去掉id ，修改相关参数。用于当前月的初始化数据
        for (IntegrationRulePo integrationRulePo1:integrationRulePosLast){
            integrationRulePo1.setId(null);
            integrationRulePo1.setRuleDate(nowDate);
            integrationRulePo1.setCreateDate(new Date());
            integrationRulePo1.setCreateUserCode("system");
        }
        //批量增加
        integrationRuleDao.batchInsert(integrationRulePosLast);
        return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
    }

    /**
     * 校验数据是否满足修改条件
     * @param dateString
     * @return
     */
    public Boolean checkModifyStatus(String dateString) {
        try {
            int nowYear = new DateTime(new Date()).getYear();
            int dataYear=new DateTime(DateUtil.string2Date(dateString,DateUtil.FORMAT_DATE_WITHOUT_DAY)).getYear();
            if (nowYear!=dataYear){
                return false;
            }else {
                int nowMonth = new DateTime(new Date()).getMonthOfYear();
                int dataMonth=new DateTime(DateUtil.string2Date(dateString,DateUtil.FORMAT_DATE_WITHOUT_DAY)).getMonthOfYear();
                return  nowMonth==dataMonth?true:false;
            }
        } catch (Exception e) {
            LOGGER.error("判断数据是否满足修改条件时出现异常{}",ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }
}
